package dfsketches.gr3d;

public class SimpleCutter implements Cutter {

	private Vertex[] v = new Vertex[3];
	private Vertex v_ = new Vertex();
	private Renderer r;
	
	public SimpleCutter(Renderer r) {
		this.r = r;
	}
	
	@Override
	public void render(Triangle t, Projector c) {
		final float dist = 1f;

		int positiveZ_count = 0;
		if (t.a.z > dist) v[positiveZ_count++] = new Vertex(t.a);
		if (t.b.z > dist) v[positiveZ_count++] = new Vertex(t.b);
		if (t.c.z > dist) v[positiveZ_count++] = new Vertex(t.c);
		
		int i = positiveZ_count;
		if (t.a.z <= dist) v[i++] = new Vertex(t.a);
		if (t.b.z <= dist) v[i++] = new Vertex(t.b);
		if (t.c.z <= dist) v[i++] = new Vertex(t.c);
		
		float kz;
		switch (positiveZ_count) {
		case 0:
			break;
		case 1:
			kz = 1 / (v[0].z - v[1].z);
			v[1].x = v[0].x - (v[0].z - dist) * (v[0].x - v[1].x) * kz;
			v[1].y = v[0].y - (v[0].z - dist) * (v[0].y - v[1].y) * kz;
			v[1].z = dist;
			kz = 1 / (v[0].z - v[2].z);
			v[2].x = v[0].x - (v[0].z - dist) * (v[0].x - v[2].x) * kz;
			v[2].y = v[0].y - (v[0].z - dist) * (v[0].y - v[2].y) * kz;
			v[2].z = dist;
			t.a = v[0];
			t.b = v[1];
			t.c = v[2];
			c.project(t);
			r.render(t);
			break;
		case 2:
			t.a = v[0];
			t.b = v[1];
			t.c = v_;
			kz = 1 / (v[0].z - v[2].z);
			v_.x = v[0].x - (v[0].z - dist) * (v[0].x - v[2].x) * kz;
			v_.y = v[0].y - (v[0].z - dist) * (v[0].y - v[2].y) * kz;
			v_.z = dist;
			c.project(t);
			r.render(t);
			kz = 1 / (v[1].z - v[2].z);
			v[0].x = v[1].x - (v[1].z - dist) * (v[1].x - v[2].x) * kz;
			v[0].y = v[1].y - (v[1].z - dist) * (v[1].y - v[2].y) * kz;
			v[0].z = dist;
			c.project(t);
			r.render(t);
			break;
		case 3:
			c.project(t);
			r.render(t);
			break;
		}
	}

}